import { Body, Controller, Delete, Get, HttpException, HttpStatus, Param, Patch, Post, Query } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { EEnableStatus } from '@/shared/types/globalEnum'
import { CreateHomeImageDto, ListPaginationHomeImageDto, UpdateHomeImageDto } from './dto/home.dto'
import { HomeService } from './home.service'

@ApiTags('后台/二期/首页配置')
@Controller('admin/home')
export class HomeController {
  constructor(private readonly homeService: HomeService) {}

  /**
   * 首页配置列表
   */
  @Get()
  list(
    @Query()
    query: ListPaginationHomeImageDto,
  ) {
    return this.homeService.findPage(query)
  }

  /**
   * 首页配置详情
   */
  @Get(':homeId')
  detail(
    @Param('homeId')
    homeId: number,
  ) {
    return this.homeService.findOne({
      homeId,
    })
  }

  /**
   * 创建首页配置
   */
  @Post()
  async create(
    @Body()
    data: CreateHomeImageDto,
  ) {
    if (data.enableStatus === EEnableStatus.ENABLED) {
      await this.homeService.setAllDisable()
    }
    return this.homeService.create(data)
  }

  /**
   * 更新首页配置
   */
  @Patch(':homeId')
  async update(
    @Param('homeId')
    homeId: number,
    @Body()
    data: UpdateHomeImageDto,
  ) {
    const findData = await this.homeService.findOne({
      homeId,
    })
    if (!findData) {
      throw new HttpException('首页配置不存在', HttpStatus.NOT_FOUND)
    }
    if (data.enableStatus === EEnableStatus.ENABLED) {
      await this.homeService.setAllDisable()
    }
    await this.homeService.update(homeId, data)
  }

  /**
   * 删除首页配置
   */
  @Delete(':homeId')
  async remove(
    @Param('homeId')
    homeId: number,
  ) {
    const findData = await this.homeService.findOne({
      homeId,
    })
    if (!findData) {
      throw new HttpException('首页配置不存在', HttpStatus.NOT_FOUND)
    }
    await this.homeService.remove(homeId)
  }
}

@ApiTags('官网/二期/首页配置')
@Controller('web/home')
export class WebHomeController {
  constructor(private readonly homeService: HomeService) {}
  /**
   * 已启用的首页配置
   */
  @Get()
  webDetail() {
    return this.homeService.findOne({
      enableStatus: EEnableStatus.ENABLED,
    })
  }
}
